package com.crack.nga2.volley;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crack.nga2.utils.GlobalConst;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 发帖、回复、编辑、引用
 * Created by Administrator on 2016/1/7.
 */
public class PostRequest extends Request<String> {
    private Response.Listener<String> listener;
    private Map<String, String> params;

    public PostRequest(String url, Map<String, String> params, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        this.listener = listener;
        this.params = params;
    }

    public PostRequest(Map<String, String> params, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        this("http://bbs.ngacn.cc/post.php", params, listener, errorListener);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", GlobalConst.Cookie);
        return headers;
    }

    @Override
    protected String getParamsEncoding() {
        return "GBK";
    }

    @Override
    public Map<String, String> getParams() {
        Log.i("tag",params.toString());
        return params;
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String json;
        try {
            json = new String(response.data, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e));
        }
        return Response.success(json, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(String response) {
        if (listener != null) {
            listener.onResponse(response);
        }
    }
}
